package com.example;

import com.example.service.ConfirmedService;
import com.example.utils.DataObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;

@SpringBootApplication
@EnableScheduling
@Slf4j
public class SpringbootLab3Application {
    @Autowired
    ConfirmedService confirmedService;

    public static void main(String[] args) {
        SpringApplication.run(SpringbootLab3Application.class, args);
    }

    //启动程序时，获取数据
    @Bean
    public CommandLineRunner commandLineRunner(){
        return args -> {
            log.info("===========启动程序，获取数据中======");
            DataObject.fetchConfirmedDataInInternet();
            //获取数据后更新Service,因为springBean初始化后才会调CommandLineRunner
            confirmedService.updateList();
            log.info("===========启动程序，获取数据结束======");
        };
    }

    //定期任务，每天凌晨1点更新数据
    @Scheduled(cron = "0 0 1 * * *")
    public void fetchConfirmedDataPeriodically(){
        try {
            //获取数据后更新Service
            DataObject.fetchConfirmedDataInInternet();
            confirmedService.updateList();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("定期获取数据错误");
        }
    }

}
